<template>
  <div class="app-Inquiry" style="margin: 0 !important;">
    <div class="top-container">
      <el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline"
        style="display: block !important;">
        <el-form-item label="后台单号" style="margin-bottom: 15px!important;">
          <el-input v-model.trim="formInline.xmbzNo" clearable size="medium" placeholder="后台单号" style="width: 163px;">
          </el-input>
        </el-form-item>
        <el-form-item label="城市" style="margin-bottom: 15px!important;">
          <el-select ref="deptRef" v-model="formInline.cityId" placeholder="城市" size="medium" style="width: 100px;" @change="handleCity">
            <el-option v-for="(house,citykey) in cityselect" :key="citykey" :label="house.deptName" :value="house.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流状态" style="margin-bottom: 15px!important;">
          <el-select ref="statusRef" v-model="formInline.state" clearable size="medium" placeholder="物流状态"
            style="width: 130px">
            <el-option v-for="item in statusList" :key="item.status" :label="item.statusName" :value="item.status" />
          </el-select>
        </el-form-item>

        <el-form-item label="分仓" style="margin-bottom: 15px!important;">
          <el-select ref="barnchWarehouseRef" v-model="formInline.warehouseId" clearable filterable size="medium"
            placeholder="分仓" style="width: 155px">
            <el-option v-for="(item,index) in barnchWarehouselist" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item sytle="dispaly:flex">
          <el-date-picker v-model="formInline.timeValue" type="datetimerange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" :picker-options="pickerOptions"
            :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
            size="medium" align="right"></el-date-picker>
        </el-form-item>
        <el-form-item style="margin-bottom: 15px!important;">
          <el-button type="primary" @click="onSubmit" size="medium" plain icon="el-icon-search"
            style="margin-left: 30px;">查询
          </el-button>
          <el-button @click="onExport" size="medium" plain icon="el-icon-download" class="ml-5 mt-0">导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table ref="table" :data="querylist" header-row-class-name="table-top" style="width: 100%">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="达达物流id">
                <span>{{ props.row.id}}</span>
              </el-form-item>
              <el-form-item label="距离">
                <span>{{ props.row.deliveryDistance }}</span>
              </el-form-item>
              <el-form-item label="接单时间">
                <span>{{ props.row.receivingTime }}</span>
              </el-form-item>
              <el-form-item label="到店时间">
                <span>{{ props.row.arriveTime }}</span>
              </el-form-item>
              <el-form-item label="取件时间">
                <span>{{ props.row.pickupTime }}</span>
              </el-form-item>
              <el-form-item label="签收时间">
                <span>{{ props.row.signTime }}</span>
              </el-form-item>
              <el-form-item label="取消时间">
                <span>{{ props.row.cancelTime }}</span>
              </el-form-item>
              <el-form-item label="创始人">
                <span>{{ props.row.createName }}</span>
              </el-form-item>
              <el-form-item label="取消人">
                <span>{{ props.row.cancelUser }}</span>
              </el-form-item>
              <el-form-item label="当前节点">
                <span>{{ props.row.traceNode }}</span>
              </el-form-item>
              <el-form-item label="当前节点备注" label-width="100px">
                <span>{{ props.row.traceMark }}</span>
              </el-form-item>
              <el-form-item label="当前节点时间" label-width="100px">
                <span>{{ props.row.traceTime }}</span>
              </el-form-item>
              <el-form-item style="width: 100%" label="收货地址">
                <span>{{ props.row.receiverAddress }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" align="center" min-width="60">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ getOrderStatus(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="商品类型" align="center"></el-table-column>
        <el-table-column prop="xmbzNo" label="单号" align="center"></el-table-column>
        <el-table-column label="城市名称" prop="cityName" align="center"></el-table-column>

        <el-table-column prop="wareName" label="仓库名称" align="center"></el-table-column>
        <el-table-column prop="waybillOrder" label="运单号" align="center"></el-table-column>
        <el-table-column prop="driverName" label="骑手" align="center"></el-table-column>
        <el-table-column prop="driverMobile" label="骑手电话"></el-table-column>
        <el-table-column prop="state" label="达达物流状态" align="center">
          <template slot-scope='scope'>
            <span>{{changeJDstatus(scope.row.state)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="responsibleDepartmentErrorText" label="部门失误类型" align="center" min-width="200">
          <template slot-scope='scope'>
            <span class="el-button--text cs-p" @click="viewResponsibleDetail(scope.row)">
              {{scope.row.responsibleDepartmentErrorText}}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryStartTime" label="配送开始时间" align="center" width="150"></el-table-column>
        <el-table-column prop="deliveryEndTime" label="配送结束时间" align="center" width="150"></el-table-column>
        <el-table-column prop="createTime" label="发布时间" align="center" width="150"></el-table-column>
        <el-table-column prop="deliveryDistance" label="配送里程" align="center"></el-table-column>
        <el-table-column prop="deliveryMoney" label="配送金额" align="center"></el-table-column>
        <el-table-column prop="cancelMoney" label="订单补偿金" align="center"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button v-show="!(scope.row.state==4||scope.row.state==5||scope.row.state==9||scope.row.state==10)" type="danger" size="mini"
              @click="cancelOrder(scope.row)">取消订单</el-button>
            <el-button type="success" size="mini" @click="handshowDayItem(scope.row)">查看日志</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="formInline.current" :limit.sync="formInline.size"
        @pagination="getList" />
    </div>

    <!-- 日志进度 -->
    <el-dialog title="日志进度" :visible.sync="islogProgress" width="50%">
      <el-radio-group v-model="reverse">
        <el-radio :label="true">倒序</el-radio>
        <el-radio :label="false">正序</el-radio>
      </el-radio-group>
      <!-- 时间线 -->
      <el-timeline :reverse="reverse" class="mt-10">
        <el-timeline-item v-for="(item, index) in this.logProgress" :key="index" :timestamp="item.createTime">
          <span>{{item.operator}}</span>
          <h3>【{{item.traceNode}}】{{item.traceMark}}</h3>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 取消订单 -->
    <el-dialog title="取消订单" :visible.sync="iscancellationOrder" width="50%">
      <div style="display: flex; align-items: center; margin-bottom: 20px;">
        <span style="margin-right: 20px">请选择取消订单选项:</span>
        <el-select v-model="iscancellationSelect" slot="prepend" placeholder="请选择取消订单选项" class="w-300">
          <el-option v-for="item in cancelOptions" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
          </el-option>
        </el-select>
      </div>
      <div style="display: flex; align-items: center;">
        <span style="width:80px">取消备注:</span>
        <el-input type="textarea" :rows="2" placeholder="请输入内容(可以不输入备注)" v-model="textarea">
        </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="iscancellationOrder = false" style="margin-right: 20px">取 消</el-button>
        <el-button type="primary" @click="goCancelorder">确 定</el-button>
      </span>
    </el-dialog>

    <complaintDetailDialog ref="complaintDetailDialog"></complaintDetailDialog>
  </div>
</template>

<script>
import {
  getWarehouseListByCityId,
  statusList
} from "@/api/pending";
import {
  citySelect, // 城市
} from "@/api/createOrder";
import {
  getDadaLogisticsOrderList,   // 列表 搜索
  showDaytitle,  // 日志授权
  dadaCancelOrder,  //取消发布订单
  exportDadaLogisticsOrderList,
  getDadaCancelName,
} from "@/api/sf-order";
import Pagination from "@/components/Pagination";
import complaintDetailDialog from '@/components/order/complaintDetailDialog'
import { download, downloadByUrl } from '@/util/file'
import { ddStatusList } from '@/const'

export default {
  components: {
    Pagination,
    complaintDetailDialog,
  },
  data() {
    return {
      cancelOptions: [],
      ischangedata: {}, //选中的数据
      textarea: '', //备注内容
      iscancellationSelect: '', //取消订单原因
      iscancellationOrder: false,  //取消订单 
      islogProgress: false, //显示日志
      logProgress: [], // 日志列表
      reverse: false, // 日志顺序
      barnchWarehouselist: [],
      total: 0,
      formInline: {
        cityId: 0, // 城市id
        xmbzNo: "", // 后台单号
        state: "",
        timeValue: [// 查询时间值
          this.dayjs(new Date()).format("YYYY-MM-DD 00:00:00"),
          this.dayjs(new Date()).format("YYYY-MM-DD 23:59:59")],
        warehouseId: '',
        current: 1,
        size: 10
      },
      querylist: [],
      Loading: true,
      statusList: ddStatusList, // 物流状态
      orderStatusList: [], // 订单状态
      pickerOptions: {
        onPick: obj => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
        disabledDate: time => {
          if (this.pickerMinDate) {
            const day1 = 31 * 24 * 3600 * 1000;
            let maxTime = this.pickerMinDate + day1;
            let minTime = this.pickerMinDate - day1;
            return time.getTime() > maxTime || time.getTime() < minTime;
          }
        }
      },
      cityselect: [], // 城市获取列表
    };
  },
  mounted() {
    citySelect().then(res => {
      res.data.data.unshift({
        id: 0,
        deptName: "全国"
      });
      this.formInline.cityId = res.data.data[0].id;
      this.cityselect = res.data.data;
    });
    this.getWarehouseList();
    // 状态列表接口
    statusList().then(res => {
      this.orderStatusList = res.data.data || [];
    });
    this.getList();

  },
  methods: {
    goCancelorder() {
      if (!this.iscancellationSelect) {
        this.$message({
          message: '请选择取消订单先选项',
          type: 'warning'
        });
        return
      }
      let data = {
        xmbzNo: this.ischangedata.xmbzNo,
        cancelReasonId: this.iscancellationSelect,
        orderId: this.ischangedata.userOrderId,
        cancelReason: this.textarea
      }
      dadaCancelOrder(data).then(res => {
        if (res.data.code == 200) {
          this.$notify({
            title: '成功',
            message: '取消订单成功',
            type: 'success'
          });
          this.iscancellationOrder = false
          this.getList()
        } else {
          this.$notify.error({
            title: '错误',
            message: '取消订单失败'
          });
        }
      })
    },
    handshowDayItem(item) {
      showDaytitle({ logisticsId: item.id, type: '1' }).then(res => {
        this.islogProgress = true
        this.logProgress = res.data.data.records
      })
    },
    changeJDstatus(status) {
      const filterStatus = ddStatusList.find(item => item.status === status)
      return filterStatus ? filterStatus.statusName : '-'
    },
    getOrderStatus(id) {
      for (let i = 0; i < this.orderStatusList.length; i++) {
        if (this.orderStatusList[i].status == id) {
          return this.orderStatusList[i].statusName;
        }
      }
    },
    getWarehouseList() {
      getWarehouseListByCityId({ cityId: this.formInline.cityId }).then(res => {
        this.barnchWarehouselist = res.data.data;
      });
    },
    onSubmit() {
      this.formInline.current = 1;
      this.getList();
    },
    onExport() {
      const params = this.getParams()
      if (this.$refs.table && this.$refs.table.selection && this.$refs.table.selection.length) {
        params.ids = this.$refs.table.selection.map(item => item.id).join(',')
      }
      downloadByUrl('/api/xmbz-sftc/dadaLogisticsOrder/export', params)
      // exportDadaLogisticsOrderList(params).then(res => {
      //   if (res.data) {
      //     download(res.data, `达达订单_${this.dayjs(new Date()).format("YYYY-MM-DD 00:00")}.xls`)
      //   } else {
      //     this.$message({
      //       message: '下载失败，请重试或联系管理员',
      //       type: 'error'
      //     })
      //   }
      // })
    },
    // 查询列表
    getList() {
      if (!this.formInline.xmbzNo &&
        (!this.formInline.timeValue || this.formInline.timeValue.length < 2)) {
        this.$message.warning('请输入搜索时间，且跨度不能超过31天');
        return false;
      }
      this.Loading = true;
      const params = this.getParams()
      getDadaLogisticsOrderList(params).then(res => {
        this.total = res.data.data.total
        this.querylist = res.data.data.rows
        setTimeout(() => {
          this.Loading = false;
        }, 0.5 * 1000);
      })
    },
    getParams() {
      const params = {
        xmbzNo: this.formInline.xmbzNo, // 后台单号
        state: this.formInline.state,
        warehouseId: this.formInline.warehouseId,
        current: this.formInline.current,
        size: this.formInline.size,
        cityId: this.formInline.cityId == 0 ? undefined : this.formInline.cityId,
        deliveryStartTime: this.formInline.xmbzNo ? '' : this.formInline.timeValue[0],
        deliveryEndTime: this.formInline.xmbzNo ? '' : this.formInline.timeValue[1],
      }
      return params
    },
    //取消订单
    cancelOrder(order) {
      this.iscancellationOrder = true
      this.ischangedata = order
      this.textarea = ''
      this.iscancellationSelect = ''
      this.getDadaCancelName(order)
    },
    getDadaCancelName(order) {
      getDadaCancelName({ dadaLogisticsOrderId: order.id }).then(res => {
        this.cancelOptions = res.data.data || []
      })
    },
    viewResponsibleDetail(order) {
      this.$refs.complaintDetailDialog.show(order)
    },
    // 获取城市
    handleCity() {
      this.formInline.warehouseId = ''
      this.getWarehouseList();
    },
  },
};
</script>

<style lang="scss" scoped>
.app-Inquiry {
  padding-right: 5px;

  .top-container {
    padding: 20px 10px 10px 20px;

    .el-form {
      .el-form-item {
        .line {
          margin: 0 3px;
          color: #8c919c;
        }
      }
    }

    .demo-form-inline {
      display: inline-block;
    }

    .el-form-item {
      margin-bottom: 20px !important;
    }
  }

  .table-container {
    padding-left: 20px;

    .table-top {
      font-size: 13px;

      th {
        padding: 5px 2px;

        .cell {
          padding: 0;
        }
      }
    }

    .el-table {
      .el-col-primary {
        margin: 0;
        padding: 2px 2px;
        font-size: 12px;
        font-weight: 400;
        border-radius: 4px;
        width: 78%;

        &.mainbutton {
          background: #ecf5ff;
          color: #409eff;
          border: 1px solid #b3d8ff;
        }

        &.dangerbutton {
          background: #fef0f0;
          color: #f56c6c;
          border: 1px solid #fbc4c4;
        }

        &.infobutton {
          background: #f4f4f5;
          color: #909399;
          border: 1px solid #d3d4d6;
        }

        &.warnbutton {
          background: #fdf6ec;
          color: #e6a23c;
          border: 1px solid #f5dab1;
        }
      }
    }

    .el-table__row {
      td {
        padding: 15px 2px;
        font-size: 13px;
        font-weight: 600;

        .cell {
          padding: 0;

          span {
            margin-left: 0;
          }
        }
      }
    }

  }
}

.el-button+ {
  .el-button {
    margin-left: 0;
    margin-top: 8px;
  }
}

.el-date-range-picker .el-picker-panel__footer .el-button--text span {
  display: none;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 33%;
}

.warning-row {
  background: oldlace;
  color: #e6a23c;
}
</style>
